package com.lt.basic.project.application.config.local;

import com.lt.basic.project.common.util.ListUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * 项目本地线程
 * @author LT
 */
public class ProThreadLocal {

    /**
     * 构造方法
     */
    public ProThreadLocal() {}

    /**
     * 取得本地线程对象
     */
    private static final ThreadLocal<Map<String, Object>> MY_LOCAL = new ThreadLocal<>();

    /**
     * 写入本地线程
     */
    public static void put(String key, Object val) {
        Map<String, Object> map = MY_LOCAL.get();
        if (map == null) {
            synchronized (MY_LOCAL) {
                map = new ConcurrentSkipListMap<>();
            }
        }
        map.put(key, val);
        MY_LOCAL.set(map);
    }

    /**
     * 获取本地线程
     */
    public static Object get(String key) {
        Map<String, Object> map = MY_LOCAL.get();
        if (map == null) {
            return null;
        }
        return map.getOrDefault(key, "");
    }


    /**
     * 获取管理员ID
     */
    public static Long getUserId() {
        Object adminId = ProThreadLocal.get("id");
        if (adminId == null || adminId.toString().isEmpty()) {
            return 0L;
        }
        return Long.parseLong(adminId.toString());
    }

    /**
     * 获取角色ID
     */
    public static List<Long> getRoleIds() {
        List<Long> roleIds = ListUtils.stringToListAsLong(ProThreadLocal.get("roleIds").toString(), ",");
        if (null == roleIds || 0 == roleIds.size()) {
            return Collections.emptyList();
        }
        return roleIds;
    }

    /**
     * 获取平台标识
     */
    public static Integer getTerminal() {
        Object adminId = ProThreadLocal.get("terminal");
        if (adminId == null || adminId.toString().equals("")) {
            return 0;
        }
        return Integer.parseInt(adminId.toString());
    }


    /**
     * 删除本地线程
     */
    public static void remove() {
        MY_LOCAL.remove();
    }

}
